package meterMonitor.controller;

import meterMonitor.constant.Constant;
import meterMonitor.consts.ResponseCode;
import meterMonitor.framework.context.CurrentUser;
import meterMonitor.framework.context.SessionContext;
import meterMonitor.model.SysUsersPO;
import meterMonitor.service.SysUsersService;
import meterMonitor.util.Sha256;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

    @Autowired
    private SysUsersService sysUsersService;

    /**
     * 用户登录
     *
     * @param mv
     * @return
     */
    @RequestMapping("/login.do")
    public ModelAndView login(ModelAndView mv) {
        return mv;
    }

    /**
     * doLogin(登录处理)
     */
    @RequestMapping("/doLogin.do")
    public @ResponseBody
    Map<String, Object> doLogin(HttpServletRequest request, @RequestParam(value = "username") String loginName, @RequestParam(value = "password") String loginPassword) {
        Map<String, Object> retMap = new HashMap<>();
        try {
            SysUsersPO userLogin = sysUsersService.getUserByName(loginName);
            // 判断用户名是否存在
            if (userLogin == null) {
                retMap.put("code", ResponseCode.DEFAULT_EXCEPTION);
                retMap.put("message", "用户名不存在！");
                return retMap;
            } else {
                // 校验密码
                String pwd = Sha256.getSHA256(loginPassword);
                if (!userLogin.getUserPwd().equals(pwd)) {
                    retMap.put("code", ResponseCode.DEFAULT_EXCEPTION);
                    retMap.put("message", "密码输入错误，请重试！");
                    return retMap;
                }
                // 判断在职状态
                if (userLogin.getState() != Constant.YES) {
                    retMap.put("code", ResponseCode.DEFAULT_EXCEPTION);
                    retMap.put("message", "员工状态异常，请联系管理员！");
                    return retMap;
                }
                CurrentUser user = new CurrentUser();
                user.setUserName(userLogin.getUserName());
                user.setNickName(userLogin.getNickName());

                List<String> authList = new ArrayList<>();
                authList.add("query");
                authList.add("edit");
                authList.add("system_auth");
                user.setUserAuthList(authList);
                user.setRoleId(userLogin.getRoleId());

                SessionContext.setCurrentUser(user);
                request.getSession().setAttribute("username", user.getUserName());
                logger.info("用户登陆ID:" + user.getUserName() + ",用户名:" + user.getNickName());
                retMap.put("code", ResponseCode.SUCCESS);
                retMap.put("message", "成功");
            }
            return retMap;
        } catch (Exception e) {
            logger.error("用户登录异常", e);
            retMap.put("code", ResponseCode.DEFAULT_EXCEPTION);
            retMap.put("message", "用户登录异常！");
            return retMap;
        }
    }

    /**
     * logOut(退出)
     */
    @RequestMapping(value = "/logout.do")
    @ResponseBody
    public Map<String, Object> logOut(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("code", ResponseCode.SUCCESS);
        if (SessionContext.getCurrentUser() != null) {
            logger.info("用户退出登陆" + SessionContext.getCurrentUser().getUserName());
            SessionContext.getSession().invalidate();
        }
        return map;
    }
}
